<?php
/*
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * File bugs here -> http://code.google.com/p/sombragmailer/issues/list
 * Contact at -> sombra2eternity@gmail.com
 * 
 * Copyright (C) 2008,2009 sombra2eternity - Thanks for play
 */
	include_once("inc_curl.php");
	$GLOBALS['curl'] = array("userAgent"=>"User-Agent=Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090910 Ubuntu/9.04 (jaunty) Shiretoko/3.5.3");

	function connect($gmailData){
		$gmailData["account"] = preg_replace("/\@gmail\.com$/","",$gmailData["account"])."@gmail.com";

		$a = array("url"=>"https://www.google.com/accounts/ServiceLoginAuth?service=mail");
		$gmailData = curlPetition($a,$gmailData);
		preg_match("/<input type=\"hidden\"[ ]*name=\"GALX\"[ ]*value=\"([^\"]*)\"/",preg_replace("/[\t\n]*/","",$gmailData['viewcode']),$arr);
		$galx = $arr[1];

		$vars = "ltmpl=default&ltmplcache=2&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3F&service=mail&rm=false&ltmpl=default";
		$vars .= "&hl=es&ltmpl=default&scc=1&GALX=".$galx."&Email=".$gmailData["account"]."&Passwd=".$gmailData["password"]."&PersistentCookie=yes&rmShown=1&signIn=Acceder&asts=";

		$a = array("url"=>"https://www.google.com/accounts/ServiceLoginAuth?service=mail","post"=>$vars);
		$gmailData = curlPetition($a,$gmailData);
		if(!preg_match("/^HTTP\/1\.1 200 OK/",$gmailData['viewcode'])){return array("connected"=>false,"currentStatus"=>array("errorCode"=>1,"errorDescription"=>"error STEP 1, exiting.","file"=>__FILE__,"line"=>__LINE__));}
		preg_match("/<meta http-equiv=\"refresh\" content=\"0; url=\&\#39;(.*?)continue=(.*?)\&\#39;\">/",$gmailData['viewcode'],$arr);

		$a = array("url"=>html_entity_decode(rawurldecode($arr[1]))."continue=".$arr[2],"followLocation"=>true);
		$gmailData = curlPetition($a,$gmailData);

		$a = array("url"=>"http://mail.google.com/mail/?ui=html&zy=e","followLocation"=>true);
		$gmailData = curlPetition($a,$gmailData);

		if(!preg_match("/<b>".$gmailData["account"]."<\/b>/",$gmailData['viewcode'])){return array("connected"=>false,"currentStatus"=>array("errorCode"=>2,"errorDescription"=>"Wrong user or password!","file"=>__FILE__,"line"=>__LINE__));}

		$gmailData['currentStatus'] = array("errorCode"=>"0","errorDescription"=>"status:connected.");
		$gmailData['connected'] = true;
		$gmailData = parseBox($gmailData);
		$gmailData['redir']="?&st=";

		return $gmailData;
	}

	function getInbox($gmailData,$type,$st="",$label=""){
		$boxArr = array("INBOX"=>"","STARRED"=>"s=r","SENTMAIL"=>"s=s","DRAFTS"=>"s=d","ALLMAIL"=>"s=a","SPAM"=>"s=m","TRASH"=>"s=t","LABEL"=>"s=l&l=".$label);
		if(!in_array($type,array_keys($boxArr))){$type = "INBOX";}
		$type = $boxArr[$type];
		$gmailData['redir']="?".$type."&st=".$st;

		$a = array("url"=>"http://mail.google.com/mail/h/".$gmailData["nextLink"]."/?".$type."&st=".$st);
		$gmailData = curlPetition($a,$gmailData);

		if(preg_match("/<\/h2><b>".$gmailData["account"]."<\/b> \| <a href=\"\?v=prg\">/",$gmailData['viewcode'])){return parseBox($gmailData);}

		$gmailData['currentStatus'] = array("errorCode"=>3,"errorDescription"=>"Error while procesing ".$type." box","file"=>__FILE__,"line"=>__LINE__);
		$gmailData['connected'] = false;
		return $gmailData;
	}

	function boxAction($gmailData,$action,$boxID,$label=""){
		$flags  = array("MARKASREAD"=>"rd","MARKASUNREAD"=>"ur","ADDSTAR"=>"st","REMOVESTAR"=>"xst","APPLYLABEL"=>"ac_".$label,"REMOVELABEL"=>"rc_".$label);
		$nvp = array("ARCHIVE"=>"&nvp_a_arch=Archivar","REPORTSPAM"=>"&nvp_a_sp=Marcar+como+spam","DELETE"=>"&nvp_a_tr=Suprimir","MARKASREAD"=>"&nvp_tbu_go=Ir","MARKASUNREAD"=>"&nvp_tbu_go=Ir","ADDSTAR"=>"&nvp_tbu_go=Ir","REMOVESTAR"=>"&nvp_tbu_go=Ir","APPLYLABEL"=>"&nvp_tbu_go=Ir","REMOVELABEL"=>"&nvp_tbu_go=Ir");
		$boxID = explode(",",$boxID);foreach($boxID as $b){$t .= "&t=".$b;}
		$vars = "redir=".urlencode($gmailData['redir'])."&tact=".$flags[$action].$nvp[$action].$t."&bact=";

		$a = array("url"=>"http://mail.google.com/mail/h/".$gmailData["nextLink"]."/".$gmailData['redir']."&at=".$gmailData['nextAt'],"followlocation"=>true,"post"=>$vars);
		$gmailData = curlPetition($a,$gmailData);

		if(preg_match("/<\/h2><b>".$gmailData["account"]."<\/b> \| <a href=\"\?v=prg\">/",$gmailData['viewcode'])){return parseBox($gmailData);}
		
		$gmailData['currentStatus'] = array("errorCode"=>2,"errorDescription"=>"Error while doing box action: ".$action,"file"=>__FILE__,"line"=>__LINE__);
		$gmailData['connected'] = false;
		return $gmailData;
	}

	function parseBox($gmailData,$debug=0){
		$code = preg_replace("/[\n|\r|\t]/",'',$gmailData['viewcode']);

		/* We take the labels */
		preg_match_all("/<a href=\"\?s=l\&l=(.*?)\"><font color=[\"]{0,1}#006633[\"]{0,1}>[^<]*<\/font><\/a>/", $code, $arrLabels);
		$gmailData["label"] = array();
		foreach($arrLabels[1] as $label){$labelDecoded = urldecode($label);$gmailData["label"][$labelDecoded] = array("name" => $labelDecoded,"link" => $label);}

		$code = str_replace(array('<font size="-2">...</font>','<font color="#cc0000">Borrador</font>'),array('&hellip;','Borrador'),$code);
		$regexMails = "/<td.*?>[ ]*<input type=[\"]{0,1}checkbox[\"]{0,1}.*?value=\"([^\"]*)\">([ ]*<img src=\"\/mail\/images\/([^\.]*)\.gif[^>]*>|)[ ]*<\/td>[ ]*<td[^>]*>[ ]*(.*?)<\/td>";
		$regexMails .= "[ ]*<td[^>]*>[ ]*(<img src=\"\/mail\/images\/paperclip.gif\"[^>]*>[ ]*|)<a.*?>.*?<font color=[\"]{0,1}#006633[\"]{0,1}>([^<]*)<\/font>";
		$regexMails .= "<\/font>[ ]*(.*?)[ ]*(<font color=[\"]{0,1}#7777CC[\"]{0,1}> - (.*?)<\/font>|)<\/[^>]*>[ ]*<\/a><\/td>[ ]*<td[^>]*>[ ]*[<b>]{0,3}([^ <]*)/";
		preg_match_all($regexMails,$code,$arrMails);
		if($debug == 1){print_r($arrMails);return;}

		$gmailData["box"] = array();
		for($a = 0; $a<count($arrMails[0]); $a++){
			$sender = $arrMails[4][$a];
			$isReaded = "yes";if(preg_match("/<b>/",$sender)){$isReaded = "no";}
			$haveAttachment = "no";if(preg_match("/paperclip/",$arrMails[5][$a])){$haveAttachment = "yes";}
			$isStarred = "no";if(preg_match("/star_on/",$arrMails[3][$a])){$isStarred = "yes";}

			if($arrMails[9][$a] == ""){$arrMails[9][$a] = " ";}
			$gmailData["box"][] = array("boxId"=>$arrMails[1][$a],"isStarred"=>$isStarred,"boxSender"=>$sender,"isReaded"=>$isReaded,"boxLabels"=>$arrMails[6][$a],"haveAttachment"=>$haveAttachment,"boxTitle"=>str_replace("'","\'",$arrMails[7][$a]),"boxSnippet"=>str_replace("'","\'",$arrMails[9][$a]),"boxDate"=>$arrMails[10][$a]);
		}
		//print_r($gmailData["box"]);

		$regexPages = "/(<a href=\"([^\"]*)\"><b>\&laquo; [a-zA-Z]*<\/b><\/a>\&nbsp;[ ]*|)(<a href=\"([^\"]*)\"><b>\&\#8249; Anterior<\/b><\/a>&nbsp;[ ]*|)<b>([0-9]*)<\/b>\&nbsp;-\&nbsp;<b>([0-9]*)<\/b>[^<]*<b>([0-9]*)<\/b>([ ]*\&nbsp;<a href=\"([^\"]*)\"><b>[a-zA-Z]* \&\#8250;<\/b><\/a>|)([ ]*\&nbsp;<a href=\"([^\"]*)\"><b>|)/";
		preg_match_all($regexPages, $code, $arrPages);
		$gmailData["pager"] = array("first"=>$arrPages[2][0],"previous"=>$arrPages[4][0],"currentBottom"=>$arrPages[5][0],"currentTop"=>$arrPages[6][0],"total"=>$arrPages[7][0],"next"=>$arrPages[9][0],"last"=>$arrPages[11][0]);

		$regexUsage = "/>[a-zA-Z ]*([0-9]{1,5}) MB[ ]*\(([0-9]{1,3})\%\)[a-zA-Z ]*([0-9]{1,5}) MB/";
		preg_match_all($regexUsage, $code, $arrUsage);
		$gmailData["usage"] = array("used"=>$arrUsage[1][0],"total"=>$arrUsage[3][0],"percentage"=>$arrUsage[2][0]);

		preg_match("/<base href=\"http:\/\/mail\.google\.com\/mail\/h\/([^\/]*)\/\">/",$code,$arrNextLink);
		$gmailData["nextLink"] = $arrNextLink[1];

		$regexNextAt = "/<form action=\"\?.*?at=([^\"&]*)[^\"]*\" name=[\"]*f[\"]* method=[\"]*POST[\"]*>/";
		preg_match_all($regexNextAt, $code, $arr);
		$gmailData["nextAt"] = $arr[1][0];
		if($debug == 1){
			print_r($arr);
			return;
		}
		return $gmailData;
	}

	function openBox($gmailData,$boxID,$overrideOP = false){
		//FIXME: implement method for last parsed box
		$a = array("url"=>"http://mail.google.com/mail/h/".$gmailData['nextLink']."/?v=c&th=".$boxID);
		/* If $overrideOP is setted, we will override URL options with this values */
		if(is_array($overrideOP)){$a['url'] .= "&".implode("&",$overrideOP);}
		//FIXME: if $overrideOP is nos set, and the box vary
		$gmailData = curlPetition($a,$gmailData);
		$viewcode = preg_replace("/[\n|\r|\t]/","",$gmailData['viewcode']);

		/* You need to provide the exact s=* box and exact st=* page where the mail is in, if this data is wrong the server
		 * will response with 302Moved and you gets nothing, this options could be overrided by the overrideOP param */
		if(preg_match("/HTTP\/1\.1 302 Moved Temporarily/",$viewcode)){return array_merge($gmailData,array('currentStatus'=>array("errorCode"=>1,"errorDescription"=>"the mail doesn't not exists or you havent got first the box where the mail is in.","file"=>__FILE__,"line"=>__LINE__),'connected'=>false,'boxOpened'=>false));}

		/* Título y labels */
		preg_match("/<b>([^<]*)<\/b><\/font><\/h2>[^<]*(.*? |)<\/table>/",$viewcode,$arr);
		$labels = "";
		if(!empty($arr[2])){preg_match_all("/<a href=\"[^\"]*\"><font[^>]*>([^<]*)<\/font><\/a>/",$arr[2],$arl);foreach($arl[0] as $k=>$v){$labels.=$arl[1][$k].",";}$labels=preg_replace("/,*$/","",$labels);}
		$boxOpened = array("boxTitle"=>$arr[1],"boxLabels"=>$labels);

		$convs = array();

		/* Expresion regular para las conversaciones, puede haber más de 1 */
		//FIXME: en la 2º linea <br clear=\"all\">[ ]*<div[^>]*><\/div>[ ]* puede que no esté si no hay attachments
		$regexMail = "/<img src=\"\/mail\/images\/star_([^_]*)_sm_2\.gif\"[^>]*><\/a>[^<]*<h3>(<a href=\"[^\"]*\"> |)<font[^>]*> (.*?) <\/font>( <\/a>|)<\/h3> &lt;([^&]*)&gt; <\/td> <td[^>]*> (<img src=\"\/mail\/images\/paperclip\.gif\"[^>]*> |)(.*?) <tr> (<td colspan=\"2\">Responder a: ([^<]*) <tr> |)<td colspan=\"2\">Para: ([^<]*) <tr> <td colspan=\"2\">";
		$regexMail .= ".*?<div class=\"msg\">(.*?)<br clear=\"all\">[ ]*<div[^>]*>";//<\/div>[ ]*<[\/]{0,1}table[^>]*>(<tr><td><table[^>]*><tr><td[^>]*><a[^\"]*\"([^\"]*)\"><img[^\/]*(\/mail\/[^\">]*)[\"]{0,1}><\/a><\/td><td[^>]*><\/td><td><b>([^<]*)<\/b><br[^>]*>([0-9]*.)|<tr><td[^>]*><b[^>]*>([0-9]*) archivos adjuntos<\/b> &#8212; <a[^\"]*\"([^\"]*)\">[^<]*<\/a> <a[^\"]*\"([^\"]*)\">[^<]*<\/a><tr><td>(.*?)<td colspan=\"2\"> <font size=\"1\">|)";
		$regexMail .= "/";
		preg_match_all($regexMail,$viewcode,$arr);

		//FIXME
		//$boxOpened['convs'][] = array("convIsStarred"=>$isStarred,"convSenderName"=>$arr[3][$a],"convSenderMail"=>$arr[5][$a],"convHaveAttachment"=>$haveAttachment,"convDate"=>$arr[7][$a],"convReplyTo"=>$arr[9][$a],"convTo"=>$arr[10][$a],"convBody"=>str_replace("'","\'",$arr[11][$a]),"convAttachmentsCount"=>count($attachments),"convAttachments"=>$attachments);


		/* Messages + attachments */
		$regex = "/<div class=\"msg\">(.*?)<\/div>[ ]*<\/table>/";
		preg_match_all($regex,$viewcode,$convArr);

		//FIXME: quiza esto solo valga para imágenes
		$regAtt = "/<table[^>]*><tr><td[^>]*><a target=_blank href=\"([^\"]*)\"><img class=thi src=([^>]*)><\/a><\/td><td[^>]*><\/td><td><b>([^<]*)<\/b><br\/>([^ ]*)[ ]*<a[^>]*>.*?<\/a>[ ]*<\/td><\/tr><\/table>/";
		foreach($convArr[0] as $k=>$v){
			if(!is_array($convs[$k])){$convs[$k]=array();}
			$convs[$k]['convBody'] = $convArr[1][$k];
			/* Si tiene attachments los listamos y modificamos el body */
			if(preg_match_all($regAtt,$convs[$k]['convBody'],$attArr)){
				$convs[$k]['convBody'] = preg_replace("/<br clear=\"all\">.*/","",$convs[$k]['convBody']);
				$convs[$k]['convAttachmentsCount'] = count($attArr[0]);
				$convs[$k]['convAttachments'] = array();
				foreach($attArr[0] as $l=>$m){
					preg_match("/attid=([0-9\.]*)&/",$attArr[1][$l],$attID);
					preg_match("/th=([0-9a-z]*)&/",$attArr[1][$l],$attBoxID);
					$convs[$k]['convAttachments'][$l]['attID'] = $attID[1];
					$convs[$k]['convAttachments'][$l]['attBoxID'] = $attBoxID[1];
					$convs[$k]['convAttachments'][$l]['attName'] = $attArr[3][$l];
					$convs[$k]['convAttachments'][$l]['attSize'] = $attArr[4][$l];
				}
			}
		}

		$boxOpened['convsCount'] = count($convs);
		$boxOpened['convs'] = $convs;

		$gmailData['boxOpened'] = $boxOpened;
		//print_r($boxOpened);

		//utilizando actualmente 1679 MB (24%) de tus 6981 MB
		$regexUsage = "/utilizando actualmente ([0-9]{1,5}) MB \(([0-9]{1,3})\%\) de tus ([0-9]{1,5}) MB/";
		preg_match_all($regexUsage, $code, $arrUsage);
		$gmailData["usage"] = array("used"=>$arrUsage[1][0],"total"=>$arrUsage[3][0],"percentage"=>$arrUsage[2][0]);

		return $gmailData;
	}

	function getAttachment($gmailData,$boxID,$attid,$saveTO = false){
		//FIXME: deprecated method
		$curl = curl_init("http://mail.google.com/mail/h/".$gmailData["nextLink"]."/?attid=".$attid."&disp=attd&view=att&th=".$boxID);
		if($GLOBALS['curl']['userAgent']){curl_setopt($curl,CURLOPT_USERAGENT,$GLOBALS['curl']['userAgent']);}
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,2);
		curl_setopt($curl,CURLOPT_COOKIEFILE,"cookie.txt");
		curl_setopt($curl,CURLOPT_COOKIEJAR,"cookie.txt");
		if($saveTO){$att = fopen($saveTO,"w");fwrite($att,curl_exec($curl));fclose($att);curl_close($curl);return true;}
		$viewcode = curl_exec($curl);
		curl_close($curl);
		return $viewcode;
	}

	function sendMail($gmailData,$to,$subject,$body,$CC="",$CCO="",$repliedBoxId="",$attachments=""){
		/* El redir es la última box que consulté, está en $gmailData['redir'], y cuando se envíe el mail
		 * seré redirigido hacia dicho redir. Aunque posiblemente podria redirigirlo hacia sent y comprobar
		 * que el mensaje se ha enviado correctamente.
		 */
		$vars = array("redir"=>$gmailData['redir'],"nvp_bu_send"=>"Enviar","to"=>$to,"subject"=>$subject,"body"=>$body);
		/* $attachments = array("0_11c0585a53ed9915_0.1","0_11c0585a53ed9915_0.2"); */

		$attGET = "";$fileCont = 0;
		if(is_array($attachments)){foreach($attachments as $attach){
			if(preg_match("/0_[^_]*_[0-9]{1}\.[0-9]{1}/",$attach)){$attGET .= "&attach=".$attach;continue;}
			$vars["file".$fileCont] = "@".realpath($attach);$fileCont++;
		}}

		$cpt = "r";
		if($repliedBoxId != ""){$cpt="r&rm=".$repliedBoxId."&th=".$repliedBoxId;}

		$a = array("url"=>"http://mail.google.com/mail/h/".$gmailData["nextLink"]."/?v=b&fv=b&cpt=".$cpt."&pv=tl&cs=c&at=".$gmailData["nextAt"].$attGET,"post"=>$vars);
		$gmailData = curlPetition($a,$gmailData);
		return $gmailData;
	}
?>
